package com.sky.orangehireserver.modules.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.orangehireserver.common.domain.Organization;
import com.sky.orangehireserver.common.service.OrganizationService;
import com.sky.orangehireserver.enums.ResponseCodeEnum;
import com.sky.orangehireserver.exception.BizException;
import com.sky.orangehireserver.modules.enterprise.dto.EnterpriseInfoUpdateDTO;
import com.sky.orangehireserver.modules.enterprise.service.EnterpriseInfoService;
import com.sky.orangehireserver.modules.enterprise.vo.EnterpriseInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 企业信息管理服务实现类
 * 
 * @author sky
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EnterpriseInfoServiceImpl implements EnterpriseInfoService {

    private final OrganizationService organizationService;

    @Override
    public EnterpriseInfoVO getCurrentEnterpriseInfo(Long orgId) {
        log.info("获取企业信息，企业ID：{}", orgId);
        
        // 检查企业是否存在
        Organization organization = organizationService.getById(orgId);
        if (organization == null) {
            throw new BizException("ORGANIZATION_NOT_FOUND", "企业不存在");
        }
        
        return convertToVO(organization);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EnterpriseInfoVO updateEnterpriseInfo(Long orgId, EnterpriseInfoUpdateDTO updateDTO) {
        log.info("更新企业信息，企业ID：{}", orgId);
        
        // 检查企业是否存在
        Organization existingOrg = organizationService.getById(orgId);
        if (existingOrg == null) {
            throw new BizException("ORGANIZATION_NOT_FOUND", "企业不存在");
        }
        
        // 检查企业状态是否为激活状态
        if (!"active".equals(existingOrg.getStatus())) {
            throw new BizException("ORGANIZATION_INACTIVE", "企业未激活，无法修改信息");
        }
        
        // 如果更新企业名称，检查新名称是否已被其他企业使用
        if (StrUtil.isNotBlank(updateDTO.getName()) && !updateDTO.getName().equals(existingOrg.getName())) {
            LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Organization::getName, updateDTO.getName())
                    .ne(Organization::getId, orgId);
            if (organizationService.count(queryWrapper) > 0) {
                throw new BizException("ORGANIZATION_NAME_EXISTS", "企业名称已存在");
            }
        }
        
        // 如果更新联系人邮箱，检查新邮箱是否已被其他企业使用
        if (StrUtil.isNotBlank(updateDTO.getContactEmail()) && !updateDTO.getContactEmail().equals(existingOrg.getContactEmail())) {
            LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Organization::getContactEmail, updateDTO.getContactEmail())
                    .ne(Organization::getId, orgId);
            if (organizationService.count(queryWrapper) > 0) {
                throw new BizException("CONTACT_EMAIL_EXISTS", "联系人邮箱已存在");
            }
        }
        
        // 更新企业信息（只更新非空字段）
        Organization updateOrg = new Organization();
        updateOrg.setId(orgId);
        updateOrg.setUpdatedAt(LocalDateTime.now());
        
        if (StrUtil.isNotBlank(updateDTO.getName())) {
            updateOrg.setName(updateDTO.getName());
        }
        if (StrUtil.isNotBlank(updateDTO.getShortName())) {
            updateOrg.setShortName(updateDTO.getShortName());
        }
        if (StrUtil.isNotBlank(updateDTO.getIndustry())) {
            updateOrg.setIndustry(updateDTO.getIndustry());
        }
        if (StrUtil.isNotBlank(updateDTO.getSize())) {
            updateOrg.setSize(updateDTO.getSize());
        }
        if (StrUtil.isNotBlank(updateDTO.getLogoUrl())) {
            updateOrg.setLogoUrl(updateDTO.getLogoUrl());
        }
        if (StrUtil.isNotBlank(updateDTO.getWebsite())) {
            updateOrg.setWebsite(updateDTO.getWebsite());
        }
        if (StrUtil.isNotBlank(updateDTO.getAddress())) {
            updateOrg.setAddress(updateDTO.getAddress());
        }
        if (StrUtil.isNotBlank(updateDTO.getContactName())) {
            updateOrg.setContactName(updateDTO.getContactName());
        }
        if (StrUtil.isNotBlank(updateDTO.getContactEmail())) {
            updateOrg.setContactEmail(updateDTO.getContactEmail());
        }
        if (StrUtil.isNotBlank(updateDTO.getContactPhone())) {
            updateOrg.setContactPhone(updateDTO.getContactPhone());
        }
        if (StrUtil.isNotBlank(updateDTO.getDescription())) {
            updateOrg.setDescription(updateDTO.getDescription());
        }
        
        // 执行更新
        boolean updated = organizationService.updateById(updateOrg);
        if (!updated) {
            throw new BizException(ResponseCodeEnum.SYSTEM_ERROR.getErrorCode(), "更新企业信息失败");
        }
        
        // 返回更新后的企业信息
        Organization updatedOrg = organizationService.getById(orgId);
        log.info("企业信息更新成功，企业ID：{}", orgId);
        return convertToVO(updatedOrg);
    }

    @Override
    public boolean isEnterpriseValid(Long orgId) {
        if (orgId == null) {
            return false;
        }
        
        Organization organization = organizationService.getById(orgId);
        return organization != null && "active".equals(organization.getStatus());
    }

    /**
     * 将Organization实体转换为EnterpriseInfoVO
     * 
     * @param organization 企业实体
     * @return 企业信息VO
     */
    private EnterpriseInfoVO convertToVO(Organization organization) {
        return BeanUtil.copyProperties(organization, EnterpriseInfoVO.class);
    }
}